<template>
  <div class="reception-container">
    <leftCardPannel>
      <patient-card :id="pid" />
    </leftCardPannel>
    <div :class="classObj" class="right-info">
      <el-tabs
        v-model="activeTags"
        type="border-card"
        :before-leave="beforeLeave"
        @tab-change="tabChange"
      >
        <el-tab-pane
          v-for="(item, index) in tabs"
          :label="item.lable"
          :key="index"
          :name="item.name"
        ></el-tab-pane>
        <router-view
          :type="pageType"
          :key="activeKey"
          :vid="vid"
          :pid="pid"
          :isTreatmentPlan="true"
        ></router-view>
      </el-tabs>
    </div>
    <el-dialog
      width="30%"
      :title="dialogText"
      v-model="isVisble"
      @closed="() => dialogRef.resetFields()"
    >
      <el-form label-width="90px" :rules="rules" :model="form" ref="dialogRef">
        <el-form-item label="体重(kg)" prop="value">
          <el-input
            placeholder="请填写体重（小数点后两位）"
            v-model="form.value"
            v-number:2
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isVisble = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit(form)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import patientCard from '@/components/PatientCard'
  import { addPatientSign } from '@/api/modules/patient'
  import { onBeforeMount, ref, reactive, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import common from '@/utils/common'
  import moment from 'moment'
  import { emrStatus } from '@/hooks/event/useEmr.js'
  // import { ElMessage } from 'element-plus'
  import { useRouteAndRouter } from '@/hooks/core/useRouteAndRouter.js'
  import router from '@/router'
  export default {
    name: 'reception',
    components: { patientCard }, //, prescription

    setup() {
      let pid = ref(null)
      let vid = ref(null)
      let form = reactive({ value: null })
      let dialogRef = ref(null)
      let store = useStore()
      let isVisble = ref(false)
      const route = useRoute()
      const dialogText = ref(null)
      // 从病历界面拿到docType
      let docType = ref(null)
      // const activeTags = ref(route.name)

      const activeTags = computed(() => {
        return route.name
      })
      const activeKey = computed(() => {
        return route.name + Date.parse(new Date())
      })
      // watch(
      //   () => route.query.vid,
      //   async () => {
      //     activeTags.value = 'MedicalRecord'
      //   }
      // )
      onBeforeMount(() => {
        if (route.query.id) {
          pid.value = parseInt(route.query.id)
          console.log('pid =' + pid.value)
        }
        if (route.query.vid) {
          vid.value = parseInt(route.query.vid)
        }
      })

      const { giveUpEditing } = emrStatus()
      const beforeLeave = async function (activeName, label) {
        const nextTabItem = tabs.value.find((item) => item.name === activeName)
        if (!store.getters.patientInfo.weight && nextTabItem.hasWeight) {
          isVisble.value = true
          console.log('tableItem = ' + JSON.stringify(nextTabItem))
          dialogText.value = `填写${nextTabItem.lable}前，请补填体重`
          return Promise.reject()
        }
        if (!route.query.emrId && nextTabItem.hasEmrId) {
          common.XmMessage(3, '当前病历未保存，请先保存病历')
          return Promise.reject()
        }
        const b = await giveUpEditing()
        if (!b) {
          return Promise.reject()
        } else {
          router.push({ name: activeName, query: route.query })
          Promise.resolve()
        }
      }

      const tabChange = function (name) {
        console.log('name =' + name)
      }
      const rules = {
        value: [{ required: true, message: '请添加体重数据', trigger: 'blur' }],
      }
      const onSubmit = async function ({ value }) {
        if (!value) return
        console.log('val =' + JSON.stringify(value))
        const fillingTime = moment()
          .locale('zh-cn')
          .format('YYYY-MM-DD HH:mm:ss')
        const params = {
          startValue: value,
          type: '4',
          patientId: pid.value,
          fillingTime,
        }
        const res = await addPatientSign(params)
        isVisble.value = false
        console.log('res =' + JSON.stringify(res))
        await store.dispatch('patient/loadPatientInfo', pid.value)
      }

      const { isRiskRx } = useRouteAndRouter()
      const emrTitle = computed(() => {
        if (isRiskRx.value) {
          return '风险筛查'
        } else {
          return '病历'
        }
      })

      // 筛查和评估
      const pageType = computed(() => {
        const item =
          tabs.value.find((item) => item.name === activeTags.value) || {}
        return item.type
      })
      const tabs = computed(() => {
        if (isRiskRx.value) {
          return [
            {
              lable: '筛查',
              name: 'riskWithScreening',
              pathName: 'riskWithScreening',
              hasWeight: true,
              type: 'screening',
            },
            {
              lable: '风险筛查',
              name: 'riskWithMedicalRecord',
              pathName: 'riskWithMedicalRecord',
              type: 'screening',
            },
            {
              lable: '评估',
              name: 'riskWithAssessment',
              pathName: 'riskWithAssessment',
              hasWeight: true,
              type: 'assessment',
            },
          ]
        } else {
          return [
            {
              lable: '筛查',
              name: 'screening',
              pathName: 'screening',
              hasWeight: true,
              type: 'screening',
            },
            {
              lable: '病历',
              name: 'medicalRecord',
              pathName: 'medicalRecord',
              type: 'screening',
            },
            {
              lable: '评估',
              name: 'assessment',
              pathName: 'assessment',
              hasWeight: true,
              type: 'assessment',
            },
            {
              lable: '治疗方案',
              name: 'treatmentPlan',
              pathName: 'treatmentPlan',
              hasEmrId: true,
              hasWeight: true,
              type: 'screening',
            },
            {
              lable: '行动计划',
              name: 'emrTreatmentActionPlan',
              pathName: 'emrTreatmentActionPlan',
              hasEmrId: true,
              hasWeight: true,
              type: 'screening',
            },
            {
              lable: '处方',
              name: 'prescription',
              pathName: 'prescription',
              hasEmrId: true,
              hasWeight: true,
              type: 'screening',
            },
          ]
        }
      })

      const classObj = computed(() => {
        return {
          // hideSidebar: !store.getters.sidebar.opened,
          hideLeftCard1: store.getters.fixedLeftCard,
        }
      })
      return {
        pid,
        activeTags,
        vid,
        beforeLeave,
        docType,
        form,
        dialogRef,
        isVisble,
        onSubmit,
        rules,
        emrTitle,
        dialogText,
        tabs,
        tabChange,
        pageType,
        activeKey,
        classObj,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .reception-container {
    padding: 32px;
    // display: flex;

    .left-info {
      // width: 20%;
    }
  }
  .right-info {
    // width: 80%;
    // padding-left: 32px;
    // flex: 1;
    margin-left: 300px;
  }
  .hideLeftCard1 {
    // background-color: yellow;
    margin-left: 25px;
  }
  // .hideLeftCard .hideLeftCard .right-info {
  //   background-color: green !important;
  // }
</style>
